package com.sky.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;

public class WechatUtil {
    public static String decryptPhone(String encryptedData, String sessionKey, String iv) {
        try {
            Security.addProvider(new BouncyCastleProvider());
            byte[] keyBytes = Base64Utils.decodeFromString(sessionKey);
            byte[] ivBytes = Base64Utils.decodeFromString(iv);
            byte[] dataBytes = Base64Utils.decodeFromString(encryptedData);
            
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
            AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
            params.init(new IvParameterSpec(ivBytes));
            cipher.init(Cipher.DECRYPT_MODE, keySpec, params);
            
            return new String(cipher.doFinal(dataBytes));
        } catch (Exception e) {
            throw new RuntimeException("解密手机号失败", e);
        }
    }
}